package unitTest;

import library.*;
import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.ExpectedException;

import java.util.List;

public class TestBooking{
	@Rule public ExpectedException thrown= ExpectedException.none();
	private Reader testUser;
	private BookingController booking;
	private BookController bookController;
	@Before
	public void setUp() throws Exception{
		DaoUtil.init();
		ReaderController readerController = new ReaderController();
		bookController = new BookController();

		try {
			testUser = readerController.getReader("testuser");
		} catch (Exception ex){
			Reader newReader = new Reader("testuser","98765432", "Hell");
			readerController.create(newReader);
			testUser = readerController.getReader("testuser");
		} finally {
			booking = new BookingController(testUser);
		}

        try{
            booking.bookRecord(1);
        } catch (Exception e){

        }
	}

    @Test
    public void returnBook() throws Exception {
        Book result = booking.returnBooked(1);
        assertNotNull(result);
    }

    @Test
    public void checkBookRecord() throws Exception {
        List<BookingRecord> result = booking.getBookingRecord();
        assertEquals("testing book item", result.get(0).getBookName());
    }

    @Test
    public void addAlreadyReserveBook() throws Exception {
        thrown.expect(Exception.class);
        thrown.expectMessage(String.format("Book %s (id:%s) already reserved and cannot booked.", bookController.getBookById(1).getName(), bookController.getBookById(1).getId()));
        booking.bookRecord(1);
    }

	@Test
	public void reserveBook() throws Exception {
		Book bk = booking.bookRecord(2);
		assertEquals(bk.getName(), bookController.getBookById(2).getName());
	}

    @Test
    public void returnNotReserveBook() throws Exception {
        Book bk = bookController.getBookById(4);
        thrown.expect(Exception.class);
        thrown.expectMessage("Book " + bk.getName() + " (id:" + bk.getId() + ") is not reserved");
        booking.returnBooked(bk);
        assertEquals(bk.getName(), bookController.getBookById(3).getName());
    }
	@After
    public void cleanUp() throws Exception {
        try{
            booking.returnBooked(1);
            booking.returnBooked(2);
        } catch (Exception e){

        }
    }

}
